﻿using System;
using System.Configuration;
using System.Web;
using Repo.Helpers;

namespace Repo.DataCaching
{
    public class Cacher
    {
        #region Internal Properties
        
        internal static int CacheInHours
        {
            get
            {
                var cacheInHours = 24; //default
                if (ConfigurationManager.AppSettings["CacheInHours"] != null
                    && int.TryParse(ConfigurationManager.AppSettings["CacheInHours"], out cacheInHours))
                {

                }
                return cacheInHours;
            }
        }

        internal static bool UseCache
        {
            get
            {
                var req = ContextHelper.Request;
                if (req != null)
                {
                    bool cacheQuery;
                    if (req.QueryString["cache"] != null
                        && bool.TryParse(req.QueryString["cache"], out cacheQuery))
                    {
                        return cacheQuery && CacheInHours != 0;
                    }
                }
                return CacheInHours != 0;
            }
        }

        #endregion

        public static T GetFromCache<T>(string key) where T : class
        {
            if (UseCache)
            {
                var items = InMemoryCache.GetItems<T>(key);
                if (items != null)
                {
                    return items;
                }
            }
            if (HttpContext.Current.Items[key] != null)
            {
                //per request cache to ensure cache is refreshed only once when using querystring cache=false
                return (T)HttpContext.Current.Items[key];
            }
            return null;
        }

        public static void SaveToCache<T>(string key, T itemToStore) where T : class
        {
            if (UseCache)
            {
                var expiry = new TimeSpan(CacheInHours, 0, 0);
                InMemoryCache.DeleteItems(key);
                InMemoryCache.SaveItems(key, itemToStore, expiry);
            }
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items.Add(key, itemToStore);
            }
        }
    }
}
